package cn.sinokj.party.chineseFourParty.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;

import org.json.JSONObject;

import java.util.Map;


import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.base.BaseActivity;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.service.HttpConstants;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.utils.PayResult;
import cn.sinokj.party.chineseFourParty.utils.Utils;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;



public class PartyListActivity extends BaseActivity implements View.OnClickListener {
    private static final int TYPE_ALIPAY = 100;
    private static final int TYPE_WEIXINPAY = 101;
    private static final int GET_PAYRESULT = 102;
    @BindView(R.id.title)
    public TextView titleText;
    @BindView(R.id.topbar_left_img)
    public View topLeftImage;
    @BindView(R.id.party_button)
    public Button pattybutton;
    @BindView(R.id.prtty_money)
    public EditText money;
    @BindView(R.id.iv_alipay_select)
    public ImageView ivAlipaySelect;
    @BindView(R.id.iv_weixin_select)
    public ImageView ivWeixinSelect;
    @BindView(R.id.rl_alipay)
    public RelativeLayout rlAlipay;
    @BindView(R.id.rl_weichatpay)
    public RelativeLayout rlWeichatpay;
    @BindView(R.id.tv_time)
    public TextView tvTime;
    @BindView(R.id.tv_party_branch)
    public TextView tvPartyBranch;
    @BindView(R.id.tv_name)
    public TextView tvName;

    private String nMoney;

    private String payInfo;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);

            // 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
//			String resultInfo = payResult.getResult();// 同步返回需要验证的信息
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                Toast.makeText(PartyListActivity.this, "支付成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(PartyListActivity.this, PartyResultActivity.class);
                intent.putExtra("nMoney", nMoney);
                startActivity(intent);
                finish();
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(PartyListActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
            }
            return true;
        }
    });
    private int payType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.party_list);
        ButterKnife.bind(this);
        titleText.setText("党费交纳");
        titleText.setVisibility(View.VISIBLE);
        topLeftImage.setVisibility(View.VISIBLE);
        tvTime.setText(App.loginInfo.getDtNow().substring(0, 7));
        tvName.setText(App.loginInfo.getVcName());
        tvPartyBranch.setText(App.loginInfo.getPartyGroupName());

        topLeftImage.setOnClickListener(this);
        pattybutton.setOnClickListener(this);
        rlAlipay.setOnClickListener(this);
        rlWeichatpay.setOnClickListener(this);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.topbar_left_img:
                finish();
                break;
            case R.id.party_button:
                nMoney = money.getText().toString().trim();
                App.nMoney = this.nMoney;
                if (TextUtils.isEmpty(nMoney)) {
                    Toast.makeText(this, "金额不能为空", Toast.LENGTH_SHORT).show();
                    break;
                }
                try {
                    double nMoneyDouble = Double.parseDouble(nMoney);
                    System.out.println(nMoneyDouble);
                    if (nMoneyDouble > 1000) {
                        Toast.makeText(this, "金额不能超过1000", Toast.LENGTH_SHORT).show();
                        break;
                    } else if (nMoneyDouble == 0) {
                        Toast.makeText(this, "金额不能为0", Toast.LENGTH_SHORT).show();
                        break;
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    Toast.makeText(this, "金额输入有误", Toast.LENGTH_SHORT).show();
                    break;
                }
                if (payType == 0) {
                    Toast.makeText(this, "请选择支付方式", Toast.LENGTH_SHORT).show();
                } else if (payType == TYPE_ALIPAY) {
                    DialogShow.showRoundProcessDialog(this);
                    new Thread(new LoadDataThread(TYPE_ALIPAY)).start();
                } else if (payType == TYPE_WEIXINPAY) {
                    DialogShow.showRoundProcessDialog(this);
                    new Thread(new LoadDataThread(TYPE_WEIXINPAY)).start();
                }

                break;
            case R.id.rl_alipay:
                ivAlipaySelect.setImageResource(R.drawable.icon_choiced);
                ivWeixinSelect.setImageResource(R.drawable.touming);
                payType = TYPE_ALIPAY;
                break;
            case R.id.rl_weichatpay:
                ivAlipaySelect.setImageResource(R.drawable.touming);
                ivWeixinSelect.setImageResource(R.drawable.icon_choiced);
                payType = TYPE_WEIXINPAY;
                break;
            default:
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(Message msg){
        if(msg.what == HttpConstants.ACTIVITY_FINISH){
            this.finish();
        }
    }

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        switch (what) {
            case TYPE_ALIPAY:
                return HttpDataService.getAliPartyInfo(nMoney, Utils.DEVICE_TYPE);
            case TYPE_WEIXINPAY:
                return HttpDataService.getWeChatPartyInfo(nMoney, Utils.DEVICE_TYPE);
        }
        return super.getDataFunction(what, arg1, arg2, obj);
    }

    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        DialogShow.closeDialog();
        if (jsonObject.optInt("nRes") != 1) {
            Toast.makeText(this, jsonObject.optString("vcRes"), Toast.LENGTH_SHORT).show();
            return;
        }

        switch (msg.what) {
            case TYPE_ALIPAY:
                payInfo = jsonObject.optString("payInfo");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PayTask alipay = new PayTask(PartyListActivity.this);
                        Map<String, String> payResult = alipay.payV2(payInfo, true);
                        Log.i("payInfo", payInfo);
                        Message msg1 = new Message();
                        msg1.obj = payResult;
                        mHandler.sendMessage(msg1);
                    }
                }).start();
                break;
            case TYPE_WEIXINPAY:
                testWxPay(jsonObject);
                App.nWeixinOrderId = jsonObject.optString("nOrderId");
              //
                break;
        }

    }


    public void testWxPay(final JSONObject jsonObject) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                PayReq request = new PayReq();
                request.appId = jsonObject.optJSONObject("payInfo").optString("appid");
                request.partnerId = jsonObject.optJSONObject("payInfo").optString("partnerid");
                request.prepayId= jsonObject.optJSONObject("payInfo").optString("prepayid");
                request.packageValue = jsonObject.optJSONObject("payInfo").optString("package");
                request.nonceStr= jsonObject.optJSONObject("payInfo").optString("noncestr");
                request.timeStamp= jsonObject.optJSONObject("payInfo").optString("timestamp");
                request.sign= jsonObject.optJSONObject("payInfo").optString("sign");
                App.msgApi.sendReq(request);
            }
        }).start();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
